import { useStore } from '@tanstack/react-store';
import meStore from '../../store/me';
import { Navigate } from 'react-router-dom';
import Loading from '../ui/Loading';

type OnlyIfAuthenticatedProps = {
  children: React.ReactNode;
};

// TODO: 高阶化
export default function OnlyIfUnauthenticated({ children }: OnlyIfAuthenticatedProps) {
  const meState = useStore(meStore, (state) => state);

  if (meState.state === 'unauthenticated') {
    return <>{children}</>;
  }

  if (meState.state === 'loading') {
    return <Loading />;
  }

  return <Navigate to="/me" />;
}
